package com.essence.grabiec104.grab.executor.handler;

import com.essence.common.model.BytesFrame;
import org.zeromq.ZMQ;

/**
 * @brief 带有PAIR套接字的抽象Handler
 * @details 带有PAIR套接字的抽象Handler，用于处理需要执行网络业务的Handler, 在责任链调用会判断next是否需要设置PAIR套接字，如果添加了新的抽象Handler,
 * 需要在doHandle中扩展判断
 */
public abstract class AbstractSocketFrameHandler implements FrameHandler {
    private FrameHandler next;
    private ZMQ.Socket workerSocket;

    @Override
    public void setNext(FrameHandler next) {
        this.next = next;
    }

    public void setWorkerSocket(ZMQ.Socket workerSocket) {
        this.workerSocket = workerSocket;
    }

    @Override
    public FrameHandler getNext() {
        return next;
    }

    /**
     * @brief 处理Frame
     * @details 处理Frame，如果未处理且存在下一个处理器，继续传递，否则返回处理结果
     */
    @Override
    public boolean handleFrame(BytesFrame frame) {
        // 当前处理器处理
        boolean isHandled = doHandle(frame);

        // 如果未处理且存在下一个处理器，继续传递
        if (next != null && isHandled) {
            if (workerSocket != null) {
                if (next instanceof AbstractSocketFrameHandler) {
                    ((AbstractSocketFrameHandler) next).setWorkerSocket(workerSocket);
                }
                // 如果有新的抽象Handler, 可以在这里扩展
            }
            return next.handleFrame(frame);
        }
        return isHandled;
    }

    protected void publish(String methodName, String requestBody) {
        if (workerSocket != null) {
            workerSocket.sendMore(methodName);
            workerSocket.send(requestBody);
        } else {
            throw new UnsupportedOperationException("未设置PAIR套接字");
        }
    }

    protected abstract boolean doHandle(BytesFrame frame);

    public abstract String getName();
}
